package com.hdaccp.hadoop.mr2;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class MusicValueApp {
    public static class MusicPartitonerMapper extends Mapper<LongWritable,Text,Text,Music>
    {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            System.out.println("mapper...");

            String line = value.toString() ;
            String[] ss = line.split("\t") ;
            String songName = ss[0] ;
            String singerName = ss[1] ;
            String gender = ss[2] ;
            String songType = ss[3] ;
            String songDive = ss[4] ;

            Music music = new Music(songName,singerName,songType,gender) ;


            context.write(new Text(gender),music);
        }
    }


    public static class MusicPartitonerReduce extends Reducer<Text,Music,Text,Music>
    {

        @Override
        protected void reduce(Text key, Iterable<Music> values, Context context) throws IOException, InterruptedException {

            for(Music t: values){
                context.write(key,t);
            }
        }


    }


    public static void main(String[] args) throws  Exception{

        if(args.length<=0){
            System.err.print("请配置参数");
            System.exit(1);
        }


        //1.读取配置文件
        Configuration cfg = new Configuration() ;
        //2.产生作业
        Job job = Job.getInstance(cfg,"job1") ;
        //3.配置作业
        job.setJarByClass(MusicValueApp.class);
        //4.1.配置作业 之 mapper
        job.setMapperClass(MusicPartitonerMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Music.class);
        //4.2配置作业 之 mapper 目标文件
        FileInputFormat.setInputPaths(job,new Path(args[0]));

        //5.1.配置作业 之 reducer
        job.setReducerClass(MusicPartitonerReduce.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        Path pathout = new Path(args[1]) ;
        //得到hdfs的文件系统
        FileSystem fileSystem = FileSystem.get(cfg) ;
        if(fileSystem.exists(pathout)){
                fileSystem.delete(pathout,true) ;
        }


        FileOutputFormat.setOutputPath(job,pathout);




        //6 提交作业

        System.exit(job.waitForCompletion(true)?0:1) ;


    }
}
